package com.think.cloud.thinkshop.mall.service.order.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.think.cloud.thinkshop.mall.controller.admin.aftersales.vo.AfterSalesOrderDetailRespVO;
import com.think.cloud.thinkshop.mall.controller.admin.order.vo.OrderDetailRespVO;
import com.think.cloud.thinkshop.mall.domain.order.OrderDetail;
import com.think.cloud.thinkshop.mall.enums.order.OrderDetailStateEnum;
import com.think.cloud.thinkshop.mall.mapper.order.OrderDetailMapper;
import com.think.cloud.thinkshop.mall.service.order.IOrderDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 订单明细Service业务层处理
 *
 * @author zkthink
 * @date 2024-05-23
 */
@Service
public class OrderDetailServiceImpl implements IOrderDetailService {

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public List<OrderDetailRespVO> selectOrderDetailListByOrderIds(List<Long> orderIds) {
        List<OrderDetailRespVO> list = orderDetailMapper.selectOrderDetailListByOrderIds(orderIds);
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(res -> {
                res.setTotalPrice(res.getPrice().multiply(new BigDecimal(res.getNum())));
                res.setImage(res.getImage().split(",")[0]);
            });
        }
        return list;
    }

    @Override
    public List<AfterSalesOrderDetailRespVO> selectOrderDetailListByAfterSalesIds(List<Long> afterSalesIds) {
        List<AfterSalesOrderDetailRespVO> list = orderDetailMapper.selectOrderDetailListByAfterSalesIds(afterSalesIds);
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(res -> {
                res.setTotalPrice(res.getPrice().multiply(new BigDecimal(res.getNum())));
                res.setImage(res.getImage().split(",")[0]);
            });
        }
        return list;
    }

    @Override
    public void updateOrderDetailByAfterSalesId(Long afterSalesId, Integer state) {
        orderDetailMapper.update(null, new LambdaUpdateWrapper<OrderDetail>()
                .eq(OrderDetail::getAfterSalesId, afterSalesId).set(OrderDetail::getState, state));
    }

    @Override
    public Boolean determineAfterSalesCompleted(Long orderId) {
        return !orderDetailMapper.exists(new LambdaQueryWrapper<OrderDetail>()
                .eq(OrderDetail::getOrderId, orderId)
                .in(OrderDetail::getState,
                        Arrays.asList(
                                OrderDetailStateEnum.NORMAL.getValue(),
                                OrderDetailStateEnum.IN_AFTER_SALES.getValue()
                        )
                )
        );
    }

}
